package com.wlf.admin.system.controller;

import com.wlf.admin.common.util.AjaxBean;
import com.wlf.admin.common.util.JSON;
import com.wlf.admin.system.domain.SysOrgan;
import com.wlf.admin.system.service.SysOrganService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * 机构控制器
 */
@RestController
@RequestMapping("/organ")
@RequiredArgsConstructor
public class OrganController {
    private final SysOrganService organService;

    @GetMapping("/main")
    ModelAndView index() {
        return new ModelAndView("/organ/index");
    }

    /**
     * 添加非根节点菜单
     */
    @GetMapping("/addForm")
    ModelAndView addFormHtml(Long id) {
        ModelAndView view = new ModelAndView("organ/add");
        SysOrgan parent;
        if (id == null) {
            parent = new SysOrgan();
            parent.setId(0L);
            parent.setName("根机构");
        } else {
            parent = organService.get(id);
        }
        view.addObject("parent", parent);
        return view;
    }

    @GetMapping("/editForm")
    ModelAndView editFormHtml(Long id) {
        ModelAndView view = new ModelAndView("organ/edit");
        SysOrgan organ = organService.get(id);
        SysOrgan parent;
        if (organ.getPid().equals(0L)) {
            parent = new SysOrgan();
            parent.setId(0L);
            parent.setName("根机构");
        } else {
            parent = organService.get(organ.getPid());
        }
        view.addObject("parent", parent);
        view.addObject("organ", organ);
        return view;
    }

    /**
     * 功能描述: 机构详情
     *
     * @author wlf 2024/2/1 14:31
     */
    @GetMapping("/infoForm")
    ModelAndView infoFormHtml(Long id) {
        ModelAndView view = new ModelAndView("organ/info");
        SysOrgan organ = organService.get(id);
        SysOrgan parent;
        if (organ.getPid().equals(0L)) {
            parent = new SysOrgan();
            parent.setId(0L);
            parent.setName("根机构");
        } else {
            parent = organService.get(organ.getPid());
        }
        view.addObject("parent", parent);
        view.addObject("organ", organ);
        view.addObject("listDto", JSON.toJSONString(organService.infoData(id)));
        return view;
    }

    @PostMapping("/list")
    AjaxBean list(SysOrgan organ) {
        return organService.getList(organ);
    }

    @PostMapping("/add")
    AjaxBean add(SysOrgan organ) {
        return organService.add(organ);
    }

    @PostMapping("/update")
    AjaxBean update(SysOrgan organ) {
        return organService.update(organ);
    }

    @GetMapping("/del")
    AjaxBean del(Long id) {
        return organService.del(id);
    }
}
